package cn.homework.mvcboot.common.exception;

import cn.homework.mvcboot.common.response.JsonResult;
import cn.homework.mvcboot.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
@Validated
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error("参数校验失败",ex);
        return JsonResult.fail(ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        // 在终端输出异常信息
        log.error("ConstraintViolationException" + ex.getMessage());
        String data = ex.getMessage();
        if(data.contains(":")){
            String error = data.split(":")[1].trim();
            // 获取id
            String id = data.split(":")[0].substring(data.indexOf(".")+1);
            log.error(id);
            data = id + ":" + error;
        }
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

}
